package cn.myframe.task.quartz;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.myframe.entity.sys.SysParameterEntity;
import cn.myframe.quartz.ScheduleJobEntity;
import cn.myframe.quartz.ScheduleUtils;
import cn.myframe.service.sys.SysParameterService;
import cn.myframe.utils.constant.STATUS;

/**
 * 
 * 
 * 
 * @author  ynz
 * @email   ynz@myframe.cn
 * @version 创建时间：2018年1月4日 下午3:18:54
 */
@Component("quartzTask")
public class QuartzTask {
	static List<ScheduleJobEntity> list = new ArrayList<ScheduleJobEntity>();
	
	@Autowired
	Scheduler scheduler;
	
	@Autowired
	SysParameterService sysParameterService;
	
	static{
		//synRecevierScheduler对应该系统参数的ParamKey的值，用系统参数来控制定时器的cron
		//list.add(new ScheduleJobEntity(1L,"freshAccessToken","thirdWX","0 30 * * * ?","freshAccessToken"));
		//list.add(new ScheduleJobEntity(2L,"freshAccessToken","pubWX","0 30 * * * ?","freshAccessToken"));
		//list.add(new ScheduleJobEntity(3L,"DBback","DbBackScheduler","0 26 11 * * ?","backupDB"));
		//list.add(new ScheduleJobEntity(12L,"logBackup","logBackupSchedule","10 1 1 * * ?","logBackup"));
		list.add(new ScheduleJobEntity(12L,"execute","printHelloWorld","0/10 * * * * ?","printHelloWorld"));
	}
	
	/**
	 * 初始化定时任务
	 */
	@PostConstruct
	public void init(){
		for(ScheduleJobEntity entity : list){
			try{
				ScheduleUtils.createScheduleJob(scheduler, entity);
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 修改系统参数时执行 
	 * @param status     
	 * @param parameter  对应系统参数的对象
	 */
	public void freshQuartz(int status, SysParameterEntity parameter){
		for(ScheduleJobEntity entity : list){
			if(entity.getJobName().equals(parameter.getParamKey())){
				if(status == STATUS.PASS.getValue()){
					entity.setCronExpression(parameter.getParamValue());
					ScheduleUtils.updateScheduleJob(scheduler, entity);
				}else if(status == STATUS.NOT_PASS.getValue()){
					ScheduleUtils.pauseJob(scheduler, entity.getJobId());
				}
			}			
		}
	}
	
	
	
	

}
